<!-- 售后管理-售后订单管理 -->
<template>
  <div class="order-management">
    <gk-title :gk-title="'售后订单管理'" />
    <tabs :isHiddenZero="true" :tabs-arr="tabArr" @returnIndex="handletabs" />
    <el-form class="search_criteria" ref="queryForm" :inline="true" label-position="right" :label-width="'110px'" :model="queryCondition" >
      <el-form-item label="订单编号：">
        <el-input v-model.trim="queryCondition.orderCode" type="text" placeholder="请输入订单编号"/>
      </el-form-item>
      <el-form-item label="订单类型：">
        <el-select v-model="queryCondition.orderType" clearable placeholder="请选择">
          <el-option
            v-for="item in typeList"
            :key="item.orderCode"
            :label="item.orderTypeName"
            :value="item.ddbm"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务类型：">
        <el-select v-model="queryCondition.busModel" clearable placeholder="请选择">
          <el-option label="批发" value="1"></el-option>
          <el-option label="长期寄售" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="退/换货原因：">
        <el-select v-model="queryCondition.returnReasonCode" clearable placeholder="请选择">
          <el-option
            v-for="item in reasonList"
            :key="item.orderCode"
            :label="item.enumVal"
            :value="item.enumKey"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品线：">
        <el-select
          v-model="queryCondition.productLineName"
          filterable
          remote
          clearable
          placeholder="请输入关键字"
          :remote-method="getProductLine"
          :loading="loading"
        >
          <el-option
            v-for="item in productLineData"
            :key="item.orderCode"
            :label="item.productLineName"
            :value="item.productLineName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="供应商：">
        <el-select
          v-model="queryCondition.supplierName"
          filterable
          remote
          clearable
          placeholder="请输入关键字"
          :remote-method="getSupplier"
          :loading="loading"
        >
          <el-option
            v-for="item in supplierData"
            :key="item.orderCode"
            :label="item.supplierName"
            :value="item.supplierName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单提交日期：">
        <el-date-picker
          v-model="commitDate"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item class="form-button">
        <el-button type="primary" @click="queryFormQuery">查询</el-button>
        <el-button @click="queryFormReset">重置</el-button>
      </el-form-item>
    </el-form>
    <section class="el-container container-box is-vertical">
      <el-editable
        height="400"
        :data="tableData"
        v-loading="tableLoading"
        :columns="userManagement"
        @selection-change="handleSelectionChange"
      >
        <template
          slot="default-action"
          slot-scope="scope">
          <el-button v-if="scope.row.orderStatus === 1"
            size="small"
            type="text text-primary"
            @click.stop="editButton(scope.row)"
          >编辑</el-button>
          <el-button v-if="scope.row.orderStatus === 11"
            size="small"
            type="text text-primary"
            @click.stop="confirmEdit(scope.row)"
          >编辑</el-button>
          <el-button v-if="scope.row.orderStatus === 1"
            size="small"
            type="text text-primary"
            @click="deletebutton(scope.row)"
          >删除</el-button>
          <el-button v-if="[2,4,5,12,10,8].includes(scope.row.orderStatus)"
            size="small"
            type="text text-primary"
            @click="viewDetails(scope.row)"
          >查看</el-button>
          <el-button v-if="scope.row.orderStatus === 4 && scope.row.isDeliver !== '1'"
            size="small"
            type="text text-primary"
            @click="editClick(scope.row)"
          >发货</el-button>
          <el-tooltip class="item" effect="dark" content="打印退回单据,同退回货物一起发给供应商" placement="top"  v-if="scope.row.orderStatus === 4">
            <el-button
              size="small"
              type="text text-primary"
              @click="getPrint(scope.row)"
            >打印</el-button>
          </el-tooltip>
        </template>
      </el-editable>
    </section>
    <el-pagination
      style="margin-top: 10px;"
      class="pagination"
      align="right"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="curPage"
      :page-sizes="PAGE_NUMBER"
      :page-size="pageSize"
      :layout="PAGINATION_LAYOUT"
      :total="totalElements"
    />
    <el-dialog
      title="发货信息"
      :visible.sync="importNew">
      <el-form label-position= 'right' label-width= '150px' class="el_form">
        <el-form-item label="快递/物流名称：" prop="name">
          <el-input style="width:70%" v-model="shippingInformation.carrierName" placeholder="请输入快递/物流名称" maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="快递单/物流单号：" prop="numbers">
          <el-input style="width:70%" v-model="shippingInformation.carrierNo" placeholder="请输入快递单/物流单号" maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="发货时间：">
          <el-date-picker style="width:70%"
            v-model="shippingInformation.deliveryTime"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <p style="color:red; margin-left:20px;">注：退回货物单据同货物一起发给供应商</p>
      </el-form>
      
      <div
        slot="footer"
        class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button
          type="primary"
          :loading="isSubmiting"
          @click="deliverGoods()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import GkTitle from '@components/gk/title/index.vue'
import tabs from '@components/tabs/index.vue'
import searchForm from '@components/gk/search/index.vue'
import ElEditable from '@components/el-editable'
import { _print } from '@const/print'
import {
  afterSalesOrderManagement,
  orderStatus,
  reasonsForReturnAndReplacement,
  statusQuantityQuery,
  printList,
  deleteOrder,
  productLine,
  supplierList,
  sendGoods
} from '@api/m_mall_web_v1.js';
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common.js'
import { tabArr, searchContent, searchContentCompact, userManagement, printContentColumns} from './const.js'
  
export default {
  components: { GkTitle, tabs, searchForm, ElEditable },
  data() {
    return {
      value1: '',
      tableLoading: false,
      loading: false,
      tabArr,
      searchContent,
      searchContentCompact,
      tableData: [],               //表格数据
      typeList: [],                //获取订单类型
      reasonList: [],              //获取退/换货原因
      orderQuantityList: [],       //获取订单数量
      userManagement,              // 表头信息
      printContentColumns,         //打印列表
      returnOrderNo: '',             //退货单号
      dealerName: '',              //经销商名称
      list: [],                    //打印内容
      curPage: 1,
      PAGE_NUMBER,                 // 页码
      PAGINATION_LAYOUT,           // 分页功能
      pageSize: PAGE_NUMBER[0],    // 一页的数量
      totalElements: 0,            // 总页数
      importNew: false,
      orderType: 2,
      printContent: '',            //打印内容
      orderIds: '',                // 删除id
      supplierData: [],            //获取供应商查询数据
      productLineData: [],            //获取产品线查询数据
      commitDate: ['', ''],        //日期查询
      orderID: '',                  //发货传的orderId
      orderCODE: '',
      isSubmiting: false,
      shippingInformation: {        //发货信息
        // orderId: '',
        carrierName: '',
        carrierNo: '',
        deliveryTime: ''
      },
      
      queryCondition: {
        orderStatus: null,
        orderCode: '',             //订单编号
        orderType: '',             //订单类型
        returnReasonCode: '',      //退换货原因
        productLineName: '',       //产品线
        supplierName: '',          //供应商
        busModel: '',
        commitDateEnd: '',
        commitDateStart: '',
        // bus_function:3
      },
      // rules: {
      //   name: [
      //     { required: true, message: '快递/物流名称长度不能超过50个字符', trigger: 'blur' },
      //   ],
      //   numbers: [
      //     { required: true, message: '快递单/物流单号长度不能超过50个字符', trigger: 'blur' },
      //   ]
      // }
    }
  },
  mounted() {
    this.getList()
    this.getOrdertype()
    this.getReasonsForReturnAndReplacement()
    this.getNumberOfStates()
    // this.getSupplier()
  },
  //获取列表数据
  methods: {
    getList() {
      this.tableLoading = true;
      const params = {
        ...this.queryCondition,
        busFunctionList: [3, 4],
        page: this.curPage,
        pageSize: this.pageSize,
        commitDateStart: this.commitDate ? this.commitDate[0] : '',
        commitDateEnd: this.commitDate ? this.commitDate[1] : '',
      }
      this.$axios.$post(afterSalesOrderManagement, params)
      .then(res => {
        if(res.code === '0'){
          this.tableData = res.payload.content
        }
        this.totalElements = res.payload.totalElements
        this.tableLoading = false;
      })
    },
    //获取订单类型
    getOrdertype() {
      const params = {
        busModel: 24,
        supplierCode: "000"
      }
      this.$axios.$post(orderStatus, params)
      .then(res => {
          this.typeList = res.payload || {}
      })
    },
    //获取退/换货原因
    getReasonsForReturnAndReplacement() {
      let params = {
        indexCode: 'returnReason',
      }
      this.$axios.$post(reasonsForReturnAndReplacement, params)
      .then(res => {
        if(res.code === '0') {
          this.reasonList = res.payload || {}
        }
      })
    },
    //获取订单各状态数量
    getNumberOfStates() {
      let params = {
        busFunctionList: [3,4]
      }
      this.$axios.$post(statusQuantityQuery, params)
      .then(res => {
        if(res.code === '0') {
          if(res.payload  === null) {
            this.tabArr[1].badge.value = 0,
            this.tabArr[2].badge.value = 0,
            this.tabArr[3].badge.value = 0,
            this.tabArr[4].badge.value = 0,
            this.tabArr[5].badge.value = 0,
            this.tabArr[7].badge.value = 0
          }
          this.tabArr[1].badge.value = res.payload.submitCount	    //待提交
          this.tabArr[2].badge.value = res.payload.checkCount	      //待平台处理
          this.tabArr[3].badge.value = res.payload.shipmentsCount	  //待发货
          this.tabArr[4].badge.value = res.payload.harvestCount	    //待供应商收货
          this.tabArr[5].badge.value = res.payload.notRefundCount	  //待退款
          // this.tabArr[6].badge.value = res.payload.refundCount	    //已退款
          this.tabArr[7].badge.value = res.payload.notarizeCount	  //待确认
          // this.tabArr[8].badge.value = res.payload.cancelCount	    //已取消
        }
      })
    },
    handletabs(index) {
      if (index === 0) {
        this.queryCondition.orderStatus = null;
      } else {
        this.tabArr.forEach((item, i) => {
          if (i === index) {
            this.queryCondition.orderStatus = item.val;
          }
        });
      }
      this.queryFormQuery()
    },
    //打印
    getPrint(row) {
      let params = {
        orderCode: row.orderCode,
      }
      this.$axios.$post(printList, params)
      .then(res => {
        if(res.code === '0') {
          this.list = res.payload.dataList || {}
          this.list.map((item,index) => {
            item.index = index + 1
            item.productCount = parseFloat(item.productCount)
          })
          this.returnOrderNo = res.payload.orderCode
          this.dealerName = res.payload.companyName
        }
        this.getPrintContent()
      })
    },
    //发货接口
    deliverGoods() {
      if(this.isSubmiting) {
        return false
      }
      this.isSubmiting = true
      this.importNew = false
      let params = {
        ...this.shippingInformation,
        orderId: this.orderID,
        orderCode: this.orderCODE
      }
      this.$axios.$post(sendGoods, params)
      .then(res => {
        this.shippingInformation= {
          carrierName: '',
          carrierNo: '',
          deliveryTime: ''
        }
        this.$message({
          type: 'success',
          message: '发货成功!',
        });
        this.getList()
        this.getNumberOfStates()
      })
      .finally(() => {
        setTimeout(() => {
          this.isSubmiting = false
        }, 1000)
      })
    },
    //发货取消按钮
    cancel() {
      this.importNew = false
      this.shippingInformation= {
        carrierName: '',
        carrierNo: '',
        deliveryTime: ''
      }
    },
    //获取打印内容
    getPrintContent() {
      let baseInfoStr = `<div style="margin:0; box-sizing:border-box; height:auto">
        <div style="border:1px solid 	#333333; border-bottom:none; padding:15px 0 15px 0;">
          <h2 style="text-align:center; margin:0;">随货退货单</h2>
        </div>
        <div style="border:1px solid 	#333333;">
          <p style="margin-left: 8px;">退货单号：${this.returnOrderNo}</p>
        </div>
        <div style="border:1px solid 	#333333;">
          <p style="margin-left: 8px;">经销商名称：${this.dealerName}</p>
        </div>
        <div style="border:1px solid 	#333333;">
          <h4 style="margin-left: 8px;">退货明细</h4>
        </div>
        <table width="100%" border="1" cellpadding="0" cellspacing="0"  >
          ${this._ListStr()}
        </table>
      </div>`
      _print(baseInfoStr, [], '0.7')
    },
    _ListStr(data = this.list) {
      let str = `<tr style="height: 50px;">
        ${this.printContentColumns.map(item => {
          return `<th style="font-size:16px; text-align:center; min-width:80px;">${item.label}</th>`
        }).join('')}
        <tr>
      `
      data.forEach((item,index) => {
        str += `
          <tr style="height:50px;">
            ${this.printContentColumns.map(col => {
              const content = ['prodPrice', 'prodAmount'].includes(col.prop) ? formatterPrice(item[col.prop]) : (item[col.prop] || '')
              return `<td style="padding:3px 0; font-size:16px; text-align:center; word-break:break-all; word-wrap:break-word;">${content}</td>`
            }).join('')}
          </tr>
        `
      })
      return str
    },
    //编辑按钮
    editButton(row) {
      if(row.busFunction === '3' && row.createType === '1') {
        this.$router.push({
          path: '/after-sale/return-order',
          query: {
            orderId: row.orderId,
          }
        })
      }
      if(row.busFunction === '3' && row.createType === '2' && row.busModel === '1') {
        this.$router.push({
          path: '/purchase-order/wholesale/list/return',
          query: {
            orderId: row.orderId,
            orderType: this.orderType
          }
        })
      }
      if(row.busFunction === '4' && row.createType === '1') {
        this.$router.push({
          path: '/after-sale/exchange-order',
          query: {
            orderId: row.orderId,
          }
        })
      }
      if(row.busFunction === '4' && row.createType === '2' && row.busModel === '1') {
        this.$router.push({
          path: '/purchase-order/wholesale/list/exchange',
          query: {
            orderId: row.orderId,
            orderType: this.orderType
          }
        })
      }
      if(row.busFunction === '4' && row.createType === '2' && row.busModel === '2') {
        this.$router.push({
          path: '/purchase-order/consign/list/exchange',
          query: {
            orderId: row.orderId,
            orderType: this.orderType
          }
        })
      }
      if(row.busFunction === '3' && row.createType === '2' && row.busModel === '2') {
        this.$router.push({
          path: '/purchase-order/consign/list/return',
          query: {
            orderId: row.orderId,
            orderType: this.orderType
          }
        })
      }
    },
    //待确认编辑跳转
    confirmEdit(row) {
      this.$router.push({
        path: '/after-sale/order-management/wait-confirm',
        query: {
          orderId: row.orderId,
        }
      })
    },
    //删除
    deletebutton(row) {
      this.$confirm('是否要删除订单?', '删除订单', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.orderIds = row;
        this.$axios.$post(deleteOrder, [this.orderIds.orderId])
        .then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!',
          });
          this.getList()
          this.getNumberOfStates()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    //获取产品线数据
    getProductLine(val) {
      if(val !== '') {
        this.loading = true
        let params = {
           productLineName: val
        }
        this.$axios.$post(productLine, params)
        .then(res => {
          if(res.code === '0') {
            this.productLineData = res.payload
            this.loading = false
          }
        })
      }
    },
    //获取供应商数据
    getSupplier(val) {
      if(val !== '') {
        this.loading = true
        let params = {
           supplierName:val
        }
        this.$axios.$post(supplierList, params)
        .then(res => {
          if(res.code === '0') {
            this.supplierData = res.payload
            this.loading = false
          }
        })
      }
    },
    //点击查询
    queryFormQuery() {
      this.curPage = 1
      this.getList()
    },
    //重置功能
    queryFormReset() {
      this.queryCondition = {
        orderStatus: this.queryCondition.orderStatus,
        orderCode: '',             //订单编号
        orderTypeId: '',           //订单类型
        returnReasonCode: '',      //退换货原因
        productLineName: '',       //产品线
        supplierName: '',          //供应商
        busModel: '',
        commitDateEnd: '',
        commitDateStart: '',
      },
      this.commitDate = ['' , ''];
      this.curPage = 1
      this.getList()
    },
    
    handleSelectionChange() {

    },
    //页码更改
    handleSizeChange(size) {
      this.curPage = 1
      this.pageSize = size
      this.getList()
    },
    // 切换不一样的页面,重置一切数据
    handleCurrentChange (curPage) {
     this.curPage = 1
     this.curPage = curPage
     this.getList()
    },
    editClick(row) {
      this.importNew = true
      this.orderID = row.orderId
      this.orderCODE = row.orderCode
    },
    //详情页跳转
    viewDetails(row) {
      this.$router.push({
        query: {
          orderId: row.orderId,
          orderCode: row.orderCode
        },
        path: `order-management/returnDetails`
      })
    }
  }
};
</script>
<style lang="less">
.order-management {
  display: flex;
  flex-direction: column;
  overflow: auto;
  padding: 0 !important;
}
.el_form{
  margin-left: 10%;
}
.search_criteria{
  margin: 0 8px;
  .el-form-item{
    margin-right: 10px;
    height: 34px;
    .el-input{
      width: 164px;
      height: 34px;
    }
    .el-form-item__content {
      height: 34px;
      line-height: 34px;
    }
    .el-range-separator {
      width: 8%;
      height: 34px;
      line-height: 34px;
    }
    .el-input__icon {
      line-height: 34px;
      height: 34px;
    }
    .el-input__inner {
      height: 34px;
    }
    .el-form-item__label {
      height: 34px;
      line-height: 34px;
    }
    .el-date-editor--datetimerange.el-input__inner {
      width: 280px;
    }
    .el-date-editor--daterange.el-input__inner {
      width: 280px;
    }
  }

  .form-button {
    float: right;
    margin-right: 0;
  }
  
}

</style>